﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Net;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.Windows.Forms;
using System.Windows.Threading;

namespace TakeNote
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        
        Server m_ServerClass = new Server();
        int tray = 0;
        string tread;

        int retray = 0;
        StreamWriter sw;
        private string m_sIPAddress;
        private int m_nPort;
        
        string sDirPath;
        string sDirectoryPath;

        NotifyIcon ni = new NotifyIcon();
        public Presentation ppt1, ppt;
        public double Window1_width = 0;


  
        public MainWindow()
        {
        
            InitializeComponent();
           FileOpenButtonIsEnabled(false);
            StreamReader tsr = File.OpenText(Environment.CurrentDirectory + "\\\\" + "trayMode.txt");
            tread = tsr.ReadLine();
            this.Topmost = false;
            //트레이
            if (tread.Equals("1"))
            {
                tray = 1;
                ni.Icon = new System.Drawing.Icon("icon.ico");
                ni.Visible = true;
                ni.DoubleClick +=
                    delegate(object sender, EventArgs args)
                    {
                        this.Show();
                        this.WindowState = WindowState.Normal;
                    };
            }
            System.Drawing.Point pt = System.Windows.Forms.Control.MousePosition;
          //  textBox4.Text = "X 좌표 : " + pt.X.ToString() + " Y 좌표 : " + pt.Y.ToString();
          //  this.Topmost = false; //MainWindow

        }
        
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {


           // this.FileOpenButtonIsEnabled(false);  // ppt 열기 false  나중에 넣을것!

            try
            {
                                m_ServerClass.WindowMain = this;
                

                string sHostName = "";
                sHostName = Dns.GetHostName();
                IPHostEntry ipHostEntry = Dns.GetHostByName(sHostName);
                IPAddress[] ipAddress = ipHostEntry.AddressList;    //  주소가져오기 현재것들을 가져오는거

                m_sIPAddress = ipAddress[0].ToString();     //주소가져오기
                m_nPort = 7800;

                m_ServerClass.ServerIP = m_sIPAddress;
                m_ServerClass.ServerPort = m_nPort;
              //  System.Windows.MessageBox.Show(m_nPort);

                textBox2.Text = m_sIPAddress;              
                textBox3.Text = m_nPort.ToString();                

                //image폴더 생성하기
                sDirPath = Environment.CurrentDirectory + "\\images";
                DirectoryInfo directory = new DirectoryInfo(sDirPath);

                if (directory.Exists == false)
                {
                    directory.Create();
                }
                // wsacancelblockingcall을 호출하여 차단 작업이 중단
                            
                //this.showin

               
                   m_ServerClass.StartSocket();
                   textBox3.Text = "서버 스타트 ";
                   buttonServerStart.IsEnabled = false;
                   //buttonServerStop.IsEnabled = true;

               
            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }                 
        }

        protected override void OnStateChanged(EventArgs e)
        {
            //트레이 상황
            if (tray == 1 && WindowState == WindowState.Minimized)
            {
                this.Hide();
            }

            //트레이 안된상황
            if (tray == 0 && WindowState == WindowState.Minimized)
            {
                ni.Visible = false;
            }

            //폼 로드(트레이 안된상태) 후 트레이 재설정
            if (retray == 1 && WindowState == WindowState.Minimized)
            {
                ni.Icon = new System.Drawing.Icon("icon.ico");
                ni.Visible = true;
                ni.DoubleClick +=
                    delegate(object sender, EventArgs args)
                    {
                        this.Show();
                        this.WindowState = WindowState.Normal;
                    };
                retray = 0;
            }
            base.OnStateChanged(e);
        }
     


        private void button1_Click(object sender, RoutedEventArgs e)     //폴더안에 삭제
        {
            
        }

        private void chx_TrayCancel_Checked(object sender, RoutedEventArgs e)
        {
         

        }

        private void chx_TrayOk_Checked(object sender, RoutedEventArgs e)
        {
          
        }

        private void btn_Tray_Click_1(object sender, RoutedEventArgs e)
        {
            
 
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                ni.Visible = false;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }   

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (Server.acceptedSocket == null){
            
              //  Console.WriteLine("접속됨");
            


            ///  1. 파일 헤더 확인           /  2. Image 저장  / 3. 파일 전송 
            ///  4. PPT Open(슬라이드활성화) /  5. 투명창열기   /  6. 파일 삭제

            Microsoft.Win32.OpenFileDialog open = new Microsoft.Win32.OpenFileDialog();
            open.Title = "    PowerPoint 선택하세요";
            open.Multiselect = false;
            open.Filter = "Images (*.PPTX)|*.PPTX|" + "All files (*.*)|*.*"; //
            sDirectoryPath = sDirPath + "\\images";

            if (((bool)open.ShowDialog()))
            {
                int i = 0;
                int z = 0;
                Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
                // 1. 파일 헤더 확인
                FileStream fs = new FileStream(open.FileName, FileMode.Open);
                BinaryReader br = new BinaryReader(fs);
                try
                {
                    int read = br.ReadInt32();
                }
                catch (SystemException ed)
                {
                    System.Windows.MessageBox.Show("제대로 된 파일이 아닙니다");
               
                }
               
                    Byte[] b = new byte[20];
                fs.Read(b, 0, 20);
                try{
                if (br.ReadInt32() == 1245184) //br.ReadInt32().ToString() == Convert.ToString(67324752) //393236
                {
                    // 2. image 저장
                    ppt1 = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                    for (i = 0; i < ppt1.Slides.Count; ++i)
                    {
                        if (i < 10)
                        {
                            ppt1.Slides[i + 1].Export(sDirectoryPath + "00"+ i + ".jpg", "jpg", (int)ppt1.Slides[i + 1].Master.Width, (int)ppt1.Slides[i + 1].Master.Height);
                        }
                        else if (i < 100)
                        {
                            ppt1.Slides[i + 1].Export(sDirectoryPath + "0" + i + ".jpg", "jpg", (int)ppt1.Slides[i + 1].Master.Width, (int)ppt1.Slides[i + 1].Master.Height);
                        }
                     }
                    ppt1.Close();  //이미지 저장하기
                    //이미지 저장햇다
                    //이제는 전송하고 실행

                    Console.WriteLine("이미지 저장 완료");
                    //예외처리 필요
                    
                    try
                    {
                        Console.WriteLine("1");
                        string selected = sDirPath;

                        Console.WriteLine(sDirPath);
                        Console.WriteLine("2");
                        
                        string[] files = System.IO.Directory.GetFiles(selected);
                        Console.WriteLine("3");
                       //---
                        foreach (string FileName in files)
                        {
                            Console.WriteLine("4");
                            System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileName);
                            long nFileSize = fileInfo.Length;
                            m_ServerClass.FileName.Add(FileName);
                            m_ServerClass.FileSize.Add((int)nFileSize);
                        }
                        m_ServerClass.DoRunning();
                       // Server.send
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message);
                    }

                    
                    while (true)
                    {
                        if(Server.Transmission_File == 1){
                             break;
                        }
                       // Console.WriteLine("파일을 보내는중입니다");
                    }
                     
                    ///////
    

                 //   ppt = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);
                    this.Topmost = false; //MainWindow               
                    this.WindowState = WindowState.Minimized;

                    ppt = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);

                    ppt.SlideShowSettings.ShowWithAnimation = Microsoft.Office.Core.MsoTriState.msoFalse;
                    //  1. ppt열기       

                    ppt.SlideShowSettings.Run();                 //슬라이드 활성화.
                    //  System.Threading.Thread.Sleep(1000);  
                    //this.WindowState = WindowState.Minimized;  //최소화시키기

                    // 2. win 열기
                    m_ServerClass.StartSockete();

                    // 6. 파일삭제
                   DirectoryInfo Dir_del = new DirectoryInfo(sDirPath);
                    FileInfo[] files1 = Dir_del.GetFiles();
                    foreach (FileInfo fi in files1)
                    {
                       fi.Delete();
                    }

                }
         
                }catch(SystemException ee){
                    System.Windows.MessageBox.Show("PPT 파일 형식이 아닙니다.");
                    }
                br.Close(); fs.Close();
            }


            //powerpoint 선택하기
          /*
            Microsoft.Win32.OpenFileDialog open = new Microsoft.Win32.OpenFileDialog();
            open.Title = "    PowerPoint 선택하세요";
            open.Multiselect = false;
            open.Filter = "Images (*.PPTX)|*.PPTX|" + "All files (*.*)|*.*";
            sDirectoryPath = sDirPath + "\\images";
            
            int i = 0;

            if (((bool)open.ShowDialog()))
            {
                Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
                ppt1 = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

                for (i = 0 ; i < ppt1.Slides.Count; ++i)
                {
                     ppt1.Slides[i + 1].Export(sDirectoryPath + i + ".jpg", "jpg", (int)ppt1.Slides[i + 1].Master.Width, (int)ppt1.Slides[i + 1].Master.Height); 
                } 
                
                ppt1.Close();  //이미지 저장하기  
              
                this.Topmost = false; //MainWindow
                ppt = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);
                            

                //  1. ppt열기       
              
                ppt.SlideShowSettings.Run();                 //슬라이드 활성화.
              //  System.Threading.Thread.Sleep(1000);  
                // 2. win 열기
                m_ServerClass.StartSockete(); 
                //Window1 win1 = new Window1();
               // win1.Topmost = true;
                //win1.Show();

         
              //  System.Threading.Thread.Sleep(1000);
              //  ppt.SlideShowWindow.View.Next();


                //////////////////////파일전송/////////////////////////////
                //string[] files = System.IO.Directory.GetFiles(sDirPath);
                //foreach (string FileName in files)
                //{
                //    long nFileSize = FileName.Length;
                //    m_ServerClass.FileName.Add(FileName);
                //    m_ServerClass.FileSize.Add((int)nFileSize);
                //}
                //m_ServerClass.DoRunning();  //파일 전송
                //////////////////////////파일삭제////////////////////////////
                //DirectoryInfo Dir_del = new DirectoryInfo(sDirPath);
                //FileInfo[] files1 = Dir_del.GetFiles();
                //foreach (FileInfo fi in files1)
                //{
                //    fi.Delete();     
                //}
                //ppt.SlideShowWindow.View.GotoSlide(12, MsoTriState.msoTrue);
                //System.Threading.Thread.Sleep(1000);
                //win1.BeginInit();
                //  win1.Activate();
            }
           */



         }
        }       
        
        private void button3_Click(object sender, RoutedEventArgs e)
        {
















            /*
            //파일전송
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog().Equals(System.Windows.Forms.DialogResult.OK))
            {
                string selected = dialog.SelectedPath;

                string[] files = System.IO.Directory.GetFiles(selected);

                foreach (string FileName in files)
                {
                    long nFileSize = FileName.Length;
                    m_ServerClass.FileName.Add(FileName);
                //   System.Windows.MessageBox.Show(FileName);
                    m_ServerClass.FileSize.Add((int)nFileSize);

                }
                    m_ServerClass.DoRunning();
        
              

                return;
            }
            */
        }

        private void buttonServerStart_Click(object sender, RoutedEventArgs e) //서버시작
        {

            try
            {
                m_ServerClass.StartSocket();              
                textBox3.Text = "서버 스타트 ";
                buttonServerStart.IsEnabled = false;
                //buttonServerStop.IsEnabled = true;
        
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }        

        }

        public void SetText(string sString)  
        {
            try
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                   //textBox5.Text= sString ;
                  
                }));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void buttonServerStop_Click(object sender, RoutedEventArgs e) //서버정지
        {
            try
            {

                m_ServerClass.StopSocket();
                buttonServerStart.IsEnabled = true;
                //buttonServerStop.IsEnabled = false;
             
             
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                m_ServerClass.CloseSocket();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
       {
            
        
           Window4 frm = new Window4();
             frm.Topmost = true;

             frm.Show();
 

             //  win1.Topmost = true;
             //  win1.Show();
              // win1.inkCanvas.Children.Add(new Line { X1 = 300, Y1 = 0, X2 = 600, Y2 = 200 });

       
       }


        public void dddd()
        {
            //   Point p1;
            //  Point p2;

            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                Console.WriteLine("머냐머냐");
                Line rr = new Line { X1 = 300, Y1 = 0, X2 = 600, Y2 = 200 };
                rr.Stroke = new SolidColorBrush(Colors.Black);
                rr.StrokeThickness = 1;
              //  Window1.Can.Children.Add(rr);
              //   Thread.Sleep(3000);
                Console.WriteLine("11");

                /*

                             Line returnLiner = new Line();
                             returnLiner.Stroke = new SolidColorBrush(Colors.Black);
                             returnLiner.StrokeThickness = 1;
                         //   while (true)
                         //   {
                
                                 p1 = new Point(300, 0);
                                 p2 = new Point(600, 600);
                                 Console.WriteLine("test1 : " + p1.X);
                                 // Console.WriteLine("test2 :" + p2.Y);
                                 returnLiner.X1 = p1.X;
                                 returnLiner.Y1 = p1.Y;
                                 returnLiner.X2 = p2.X;
                                 returnLiner.Y2 = p2.Y;
                
                               //inkCanvas.Children.Add(returnLiner);
                                 //Thread.Sleep(3000);
                           // }

                  */
            }));



        }

        public void FileOpenButtonIsEnabled(bool qBool)
        {
            try
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                    button2.IsEnabled = qBool;
                }));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
          //  DragMove();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void button1_Click_2(object sender, RoutedEventArgs e)
        {
            m_ServerClass.StartSockete();
        }

        private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
        {

        }



    }
}



